package com.lmxdawn.api.common.session;

import cn.hutool.extra.spring.SpringUtil;
import com.lmxdawn.api.admin.entity.auth.AuthAdmin;
import com.lmxdawn.api.admin.service.auth.AuthAdminService;
import com.lmxdawn.api.common.exception.NotLoginException;
import com.lmxdawn.api.common.exception.NotReadTipException;
import com.lmxdawn.api.dnf.annotation.LoginIgnore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Objects;

/**
 * 会话拦截器，Controller 方法调用前处理
 *
 * @author jy
 * @since 2023-12-04 14:54
 */
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            LoginIgnore loginIgnore = method.getAnnotation(LoginIgnore.class);
            if (null != loginIgnore) {
                // 忽略拦截
                return true;
            }
            String tokenValue = TokenHelper.getTokenValue(request);
            if (StringUtils.isEmpty(tokenValue)) {
                log.error("==========req url :{}", request.getRequestURI());
                throw new NotLoginException();
            }
            SessionStrategy sessionStrategy = SessionHelper.getSessionStrategy();
            UserSession userSession = sessionStrategy.getUserSession(request);
            if (Objects.isNull(userSession)) {
                throw new NotLoginException();
            }
//            if (!userSession.isRealName() && !(request.getRequestURI().contains("saveTipsRead")
//                    || request.getRequestURI().contains("/realname/auth"))) {
//                throw new NotRealnameException();
//            }

            AuthAdminService authAdminService = SpringUtil.getBean(AuthAdminService.class);
            AuthAdmin authAdminUp = new AuthAdmin();
            authAdminUp.setId(userSession.getId());
            authAdminUp.setLastLoginTime(new Date());
            authAdminService.updateAuthAdmin(authAdminUp);
            if (!userSession.isTipRead()  && !(request.getRequestURI().contains("saveTipsRead")
                || request.getRequestURI().contains("/realname/auth"))) {
                throw new NotReadTipException();
            }
            // 写入线程上下文
            SessionContextHolder.set(userSession);
        }
        // 通过拦截
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 清楚
        SessionContextHolder.remove();
    }

}
